package com.codeoss.framework.workflow.parser;

import org.springframework.stereotype.Service;

import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.ExpressionUtil;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.workflow.def.LineDef;
import com.codeoss.framework.workflow.def.WorkflowElementDef;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service
public class LineParser implements IWorkflowElementParser{

	@Override
	public WorkflowElementDef parse(IWorkflowElementParseContext workflowElementParseContext, ObjectNode objectNode) {
		// TODO Auto-generated method stub
		LineDef lineDef=new LineDef();
		JsonNode jsonNode=objectNode.get("from");
		lineDef.setFromNodeId(jsonNode.asText());
		
		jsonNode=objectNode.get("to");
		lineDef.setToNodeId(jsonNode.asText());
		
		jsonNode=objectNode.get("label");
		if(jsonNode!=null) {
			String label=jsonNode.asText();
			if (!StringUtils.isEmpty(label) && !"null".equals(label)) {
				lineDef.setLabel(label);
			}
		}
		
		jsonNode=objectNode.get("condition");
		if(jsonNode!=null) {
			String condition=jsonNode.asText();
			if (!StringUtils.isEmpty(condition) && !"null".equals(condition)) {
				Expression expression = ExpressionUtil.convertToExpression(condition,
						Expression.EXPRESSION_TYPE_JAVASCRIPT);
				lineDef.setCondition(expression);
			}
		}
		
		jsonNode=objectNode.get("takeEventExpression");
		if(jsonNode!=null) {
			String takeEventExpression=jsonNode.asText();
			if (!StringUtils.isEmpty(takeEventExpression) && !"null".equals(takeEventExpression)) {
				Expression expression = ExpressionUtil.convertToExpression(takeEventExpression,
						Expression.EXPRESSION_TYPE_JAVASCRIPT);
				lineDef.setTakeEventExpression(expression);
			}
		}
		
		jsonNode=objectNode.get("name");
		lineDef.setName(jsonNode.asText());
		return lineDef;
	}

}
